package com.pray.praymall.cart.interceptor;

import com.pray.common.constant.AuthServerConstant;
import com.pray.common.constant.CartConstant;
import com.pray.common.vo.MemberResponseVo;
import com.pray.praymall.cart.vo.UserInfoTo;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 执行目标方法之前，判断用户的登录状态，并封装传递给controller目标请求
 *
 * @author 魂悸魄
 * @date 2020/9/23 22:15
 */
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    /**
     * 作用于目标方法执行之前
     *
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     * @param handler  handler
     * @return always return true
     * @throws Exception not throw
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo userInfoTo = new UserInfoTo();

        MemberResponseVo loginUser = (MemberResponseVo) request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
        if (loginUser != null) {
            // 用户登录了
            userInfoTo.setUserId(loginUser.getId());
        }

        // 得到名为user-key的cookie的值
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (CartConstant.TEMP_USER_COOKIE_NAME.equals(cookie.getName())) {
                    userInfoTo.setHasCookie(true);
                    userInfoTo.setUserKey(cookie.getValue());
                }
            }
        }

        // 如果没有临时用户一定分配一个临时用户
        if (StringUtils.isEmpty(userInfoTo.getUserKey())) {
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
        }

        // 将信息封装到ThreadLocal里
        threadLocal.set(userInfoTo);
        return true;
    }

    /**
     * 业务执行之后，分配临时用户，让浏览器保存
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @param handler handler
     * @param modelAndView ModelAndView
     * @throws Exception not throw
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 没有user-key这个cookie才需要设置cookie
        if (!threadLocal.get().isHasCookie()) {
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, threadLocal.get().getUserKey());
            cookie.setDomain("praymall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
